import { Button, ConfigProvider, Form, Input, Select, Table, Icon } from 'antd';
import React, { useEffect, useState, useRef, useImperativeHandle, forwardRef } from 'react';
import Modal from '../../../components/Modal';
import useDataType from './data-type';
import ParamsTypeSet from './paramsTypeSet';
import { compare } from '../../../utils/compare';
import { randomKey } from '../../../utils/utils';
import { PARAME_TYPE } from '../../../utils/constant';

const EmptyNode = (onClick, actionType) => {
  return function(props) {
    return (
      <div>
        暂无参数
        {actionType !== 'detail' && (
          <>
            ，
            <Button onClick={onClick} type='link' size='small'>
              立即添加
            </Button>
          </>
        )}
      </div>
    );
  };
};
const Params = forwardRef((props, ref) => {
  const { getFieldDecorator, getFieldValue, setFieldsValue } = props.form;

  const [ps, setPs] = useState([]);
  const types = useDataType();
  const paramsTypeSetRef = useRef();

  useImperativeHandle(ref, () => ({
    getPs: () => ps,
  }));

  useEffect(() => {
    if (props.value) {
      const data = props.value.map((o) => {
        return {
          // 加入ukey
          key: randomKey(),
          ...o,
        };
      });
      setPs(data);
    }
  }, [props.value]);

  const removePs = (evt) => {
    const { index } = evt.currentTarget.dataset;
    const params = getFieldValue('params');
    const arr = [...ps];
    arr.splice(index, 1);
    params.splice(index, 1);
    setPs(arr);
    setFieldsValue({ params });
  };

  const handleParameTypeChange = (_, index) => {
    const temp = [...ps];
    temp[index]['varEnums'] = [];
    setPs(temp);
  };

  const handleSet = (index) => {
    const disabled = props.actionType === 'detail';
    const parame_type = getFieldValue(`params[${index}].showType`);
    const enumsValueJson = parame_type === 1 ? ps[index]['varTypeLimit'] : ps[index]['varEnums'];
    const key = Modal.open({
      title: parame_type === 1 ? '配置参数输入范围 ' : '配置枚举值',
      width: '700px',
      isOkBtn: !disabled,
      isCancelBtn: !disabled,
      content: (
        <ParamsTypeSet
          {...props}
          parame_type={parame_type}
          ref={paramsTypeSetRef}
          value={enumsValueJson}
          disabled={disabled}
          compareData={(props.compareData && props.compareData[index] && props.compareData[index].varEnums) || []}
        />
      ),
      ok: () => {
        const enumsValueJson = paramsTypeSetRef.current.getJson();
        const temp = [...ps];
        if (parame_type === 1) {
          temp[index]['varEnums'] = [];
          temp[index]['varTypeLimit'] = enumsValueJson;
        } else {
          temp[index]['varTypeLimit'] = [];
          temp[index]['varEnums'] = enumsValueJson;
        }

        setPs(temp);
        Modal.close(key);
      },
      cancel: () => {
        Modal.close(key);
      },
    });
  };

  const addParam = () => {
    setPs(
      ps.concat([
        {
          // 加入ukey
          key: randomKey(),
          name: '',
          type: '',
          isNull: 1,
          remark: '',
          showType: 1,
        },
      ]),
    );
  };
  const paramsCols = [
    {
      title: '序号',
      dataIndex: 'index',
      width: 80,
      render(_, __, index) {
        return index + 1;
      },
    },
    {
      title: '参数CODE',
      dataIndex: 'code',
      width: 130,
      render(_, __, index) {
        return 'p' + (index + 1);
      },
    },
    {
      title: '参数名称',
      dataIndex: 'name',
      width: 180,
      render(text, _, index) {
        return (
          <Form.Item className='fn-param-item'>
            {getFieldDecorator(`params[${index}].name`, {
              initialValue: text || '',
              rules: [{ max: 128, message: '最长128个字符' }],
            })(<Input style={compare(props, index, 'name')} disabled={props.actionType === 'detail'} />)}
          </Form.Item>
        );
      },
    },
    {
      title: <span className='ant-form-item-required'>参数类型</span>,
      dataIndex: 'type',
      width: 180,
      render(text, _, index) {
        return (
          <Form.Item className='fn-param-item' style={compare(props, index, 'type')}>
            {getFieldDecorator(`params[${index}].type`, {
              rules: [{ required: true, message: '请选择' }],
              id: 'type' + index,
              initialValue: text || '',
            })(
              <Select
                style={{ width: '100%', ...compare(props, index, 'type') }}
                disabled={props.actionType === 'detail'}
              >
                {types.map((o) => {
                  return <Select.Option key={o.code}>{o.name}</Select.Option>;
                })}
              </Select>,
            )}
          </Form.Item>
        );
      },
    },
    {
      title: <span className='ant-form-item-required'>参数框类型</span>,
      dataIndex: 'showType',
      width: 220,
      render: (text, _, index) => (
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Form.Item className='fn-param-item' style={{ width: '85%' }}>
            {getFieldDecorator(`params[${index}].showType`, {
              rules: [{ required: true, message: '请选择' }],
              id: 'showType' + index,
              initialValue: text || 1,
            })(
              <Select
                style={{ width: '100%', ...compare(props, index, 'showType') }}
                disabled={props.actionType === 'detail'}
                onChange={(value) => handleParameTypeChange(value, index)}
              >
                {PARAME_TYPE.map((item, index) => {
                  return (
                    <Select.Option key={item} value={index + 1}>
                      {item}
                    </Select.Option>
                  );
                })}
              </Select>,
            )}
          </Form.Item>

          <Icon type='setting' style={{ fontSize: '16px', color: '#777' }} onClick={() => handleSet(index)} />
        </div>
      ),
    },
    {
      title: <span className='ant-form-item-required'>是否可为空</span>,
      dataIndex: 'isNull',
      width: 150,
      render(text, _, index) {
        return (
          <Form.Item className='fn-param-item'>
            {getFieldDecorator(`params[${index}].isNull`, {
              rules: [{ required: true, message: '请选择' }],
              id: 'null' + index,
              initialValue: text !== 0 ? 1 : 0,
            })(
              <Select
                style={{ width: '100%', ...compare(props, index, 'isNull') }}
                disabled={props.actionType === 'detail'}
              >
                <Select.Option value={1}>允许为空</Select.Option>
                <Select.Option value={0}>不能为空</Select.Option>
              </Select>,
            )}
          </Form.Item>
        );
      },
    },
    {
      title: '参数备注',
      dataIndex: 'remark',
      width: 180,
      render(text, _, index) {
        return (
          <Form.Item className='fn-param-item'>
            {getFieldDecorator(`params[${index}].remark`, {
              initialValue: text || '',
              rules: [{ max: 256, message: '最长256个字符' }],
            })(<Input style={compare(props, index, 'remark')} disabled={props.actionType === 'detail'} />)}
          </Form.Item>
        );
      },
    },
    props.actionType !== 'detail' && {
      title: '操作',
      render(text, r, index) {
        return (
          <Button size='small' type='link' onClick={removePs} data-index={index}>
            删除
          </Button>
        );
      },
    },
  ]
    .filter(Boolean)
    .map((o) => {
      return {
        key: o.dataIndex,
        ...o,
      };
    });

  return (
    <div>
      <h3>选择参数</h3>
      <br />
      <ConfigProvider renderEmpty={EmptyNode(addParam, props.actionType)}>
        <Table pagination={false} columns={paramsCols} scroll={{ x: true }} dataSource={ps} bordered={false} />
      </ConfigProvider>
      {ps.length > 0 && props.actionType !== 'detail' && (
        <div className='mart10' style={{ textAlign: 'center' }}>
          <Button onClick={addParam}>添加一行</Button>
        </div>
      )}
    </div>
  );
});

export default Params;
